<script setup lang="ts">
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Refresh } from "@element-plus/icons-vue";
import {
  addClassApi,
  classDataApi,
  delClassApi,
  getClassByIdApi,
  modifyClassApi,
} from "@/http/Api/teachers/classManageApi";
import {
  teacherLoginApi,
  projectManagerApi,
} from "@/http/Api/teachers/employeeApi";
import { majorListApi } from "@/http/Api/teachers/MajorApi";
import { getClassroomApi } from "@/http/Api/teachers/classroomManageApi";

const title = ref("新增班级");

// 搜索部分
// const searchFormRef = ref<FormInstance>();
// const searchCondition = reactive({
//   name: "",
//   status: "",
//   subject: "",
// });
// const onSearchSubmit = () => {
//   console.log("submit!");
// };
// const resetSearchForm = (formEl: FormInstance | undefined) => {
//   if (!formEl) return;
//   formEl.resetFields();
// };

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  currentPage.value = val;
  getClassInitData();
};

// 班级信息
const classData = ref([]);
const total = ref(0);
const modalState = ref("ADD");
const classFormRef = ref<FormInstance>();

const state = reactive({
  // 当前班级信息
  classForm: {
    id: "",
    baiJieName: "",
    classroomId: "",
    classAdviserMessageId: "",
    majorId: "",
    projectManagerMessageId: "",
    status: 1,
  },
  statusData: [
    {
      code: 1,
      text: "可用",
    },
    {
      code: 2,
      text: "已结业",
    },
  ],
  classAdviserMessage: [
    // 班主任
    {
      id: 1,
      username: "曾娜",
    },
  ],
  classroom: [
    // 教室
    {
      classroomId: 1,
      classroomName: "9教",
    },
    {
      classroomId: 3,
      classroomName: "19教",
    },
    {
      classroomId: 2,
      classroomName: "20教",
    },
  ],
  major: [
    // 技术方向
    {
      id: 0,
      majorName: "Java",
    },
  ],
  pm: [
    // 项目经理
    {
      id: 1,
      majorId: "4",
      username: "李满",
    },
  ],
});
const { classAdviserMessage, classroom, major, pm, classForm, statusData } =
  toRefs(state);

const majorPm = computed(() => {
  console.log(classForm.value.majorId);
  const p = pm.value.filter((item) => item.majorId == classForm.value.majorId);
  console.log("根据方向筛选pm：", p);
  return p;
});

// 班级信息验证
const classRules = reactive<FormRules>({
  baiJieName: [
    { required: true, message: "请输入百杰班级名字", trigger: "blur" },
    { min: 3, max: 10, message: "Length should be 3 to 10", trigger: "blur" },
  ],
  classAdviserMessageId: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  classroomId: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  majorId: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  projectManagerMessageId: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
});

// 列表请求
async function getClassInitData() {
  try {
    const res = await classDataApi({
      page: currentPage.value,
      size: pageSize.value,
    });
    console.log("班级列表请求：", res);
    if (res.data.code == "200") {
      classData.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      ElMessage.error(res.data.msg);
    }
  } catch (err) {
    console.log("请求失败：", err);
    ElMessage.error("请求失败，请稍后重试!");
  }
}
// 模态框关联数据请求
async function getModalData() {
  try {
    const resMajorList = await majorListApi();
    const resTeacher = await teacherLoginApi();
    const resProjectManager = await projectManagerApi();
    const resClassroom = await getClassroomApi({});

    console.log("关联数据 resMajorList：", resMajorList.data);
    console.log("关联数据 resTeacher：", resTeacher.data);
    console.log("关联数据 resProjectManager：", resProjectManager.data);
    console.log("关联数据 resClassroom：", resClassroom.data);
    major.value = resMajorList.data.data;
    classAdviserMessage.value = resTeacher.data.data;
    pm.value = resProjectManager.data.data;
    classroom.value = resClassroom.data.data;
  } catch (err) {
    console.log("新增班级请求失败：", err);
    ElMessage.error("请求失败，请稍后重试!");
  }
}
onMounted(() => {
  getClassInitData();
  getModalData();
});
// 刷新数据
const refreshClassData = () => {
  modalState.value = "ADD";
  currentPage.value = 1;
  getClassInitData();
};

// 模态框
const classDialogVisible = ref(false);
const onCloseDialog = () => {
  // console.log("关闭模态框");
  classFormRef.value!.resetFields();
};
// 打开新增模态框
const onOpenAddClassDialog = () => {
  classDialogVisible.value = true;
  modalState.value = "ADD";
  title.value = "新增班级";
};

// 提交数据
const submitClassForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (!valid) return console.log("error submit!", fields);

    console.log("submit - " + modalState.value, classForm);

    try {
      const res =
        modalState.value == "ADD"
          ? await addClassApi(classForm.value)
          : await modifyClassApi(classForm.value);

      console.log("班级结果：", res);

      if (res.data.code == "200") {
        classDialogVisible.value = false;

        ElMessage({
          type: "success",
          message: res.data.msg,
        });
      } else {
        ElMessage.error(res.data.code.msg);
      }
    } catch (err) {
      console.log("班级请求失败：", err);
      ElMessage.error("请求失败，请稍后重试!");
    }
  });
};
// 删除班级数据
const onDelClass = async (row: any) => {
  ElMessageBox.confirm("确认删除该条信息吗?", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        console.log(row);
        const res = await delClassApi(row.id);
        console.log("删除班级数据结果：", res);

        if (res.data.code == "200") {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          getClassInitData();
        } else {
          ElMessage.error(res.data.msg);
        }
      } catch (err) {
        console.log("删除班级请求失败：", err);
        ElMessage.error("请求失败，请稍后重试!");
      }
    })
    .catch(() => {
      console.log("取消删除");
    });
};

// 查看班级信息
const onViewClass = (row: any) => {
  console.log(row);
  modalState.value = "VIEW";
  title.value = "查看班级";
  getClassByIdApi(row.id)
    .then((res) => {
      console.log("查看班级信息：", res.data);
      classForm.value = res.data.data;
    })
    .catch((err) => {
      console.log("查看班级信息：", err);
    });
  classDialogVisible.value = true;
};
// 编辑班级信息
const onEditClass = (row: any) => {
  console.log(row);
  modalState.value = "EDIT";
  title.value = "编辑班级";
  getClassByIdApi(row.id)
    .then((res) => {
      classForm.value = res.data.data;
    })
    .catch((err) => {
      console.log("获取班级信息失败：", err);
    });
  classDialogVisible.value = true;
};

// 表单重置
const resetClassForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<template>
  <main>
    <div class="page-header">
      <div class="page-title">
        <p>班级管理</p>
      </div>
    </div>
    <div class="page-body">
      <!-- 搜索 -->
      <!-- <div class="search">
        <el-form ref="searchFormRef" :inline="true" :model="searchCondition" class="demo-form-inline">
          <el-form-item label="班级">
            <el-input v-model="searchCondition.name" size="small" style="width: 100px;" />
          </el-form-item>
          <el-form-item label="方向">
            <el-select v-model="searchCondition.subject" class="m-2" size="small" style="width: 100px;">
              <el-option v-for="item in subjects" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchCondition.status" class="m-2" size="small" style="width: 100px;">
              <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="onSearchSubmit">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="resetSearchForm(searchFormRef)">重置</el-button>
          </el-form-item>
        </el-form>
      </div> -->

      <!-- 批量操作 -->
      <div class="batch-processing">
        <div>
          <el-button type="primary" link @click="onOpenAddClassDialog"
            >新增班级</el-button
          >
        </div>
        <el-icon class="class_refresh" :size="22" @click="refreshClassData"
          ><Refresh
        /></el-icon>
      </div>

      <!-- 班级列表 -->
      <div class="student-list">
        <el-table
          :data="classData"
          stripe
          border
          style="width: 100%; min-width: 630px"
        >
          <!-- <el-table-column type="selection" width="55" /> -->
          <el-table-column label="序号" width="54">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="baiJieName" label="班级名称" width="82" />
          <!-- <el-table-column prop="num" label="班级人数" width="90" /> -->
          <el-table-column prop="adviserName" label="班主任" width="80" />
          <el-table-column prop="majorName" label="技术方向" width="82" />
          <el-table-column prop="pmName" label="项目经理" width="82" />
          <!-- <el-table-column prop="status" label="班级状态" width="90" /> -->
          <el-table-column prop="classroomName" label="教室" width="56" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button link size="small" @click="onViewClass(scope.row)"
                >查看</el-button
              >
              <el-button
                link
                size="small"
                type="warning"
                @click="onEditClass(scope.row)"
                >编辑</el-button
              >
              <el-button
                link
                size="small"
                type="danger"
                @click="onDelClass(scope.row)"
                >删除</el-button
              >
              <!-- <el-button link size="small">导入学员</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <el-pagination
        small
        background
        layout="prev, pager, next"
        :total="total"
        class="mt-4"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="classDialogVisible"
      :title="title"
      width="60%"
      @close="onCloseDialog"
    >
      <el-form
        ref="classFormRef"
        :model="classForm"
        :rules="classRules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="班级id">
          <el-input :value="classForm.id" disabled />
        </el-form-item>
        <el-form-item label="班级名字" prop="baiJieName">
          <el-input
            v-model="classForm.baiJieName"
            placeholder="请输入班级名字"
            :disabled="modalState == 'VIEW'"
          />
        </el-form-item>
        <el-form-item label="班主任" prop="classAdviserMessageId">
          <el-select
            v-model="classForm.classAdviserMessageId"
            placeholder="请选择班主任"
            :disabled="modalState == 'VIEW'"
          >
            <el-option
              v-for="item in classAdviserMessage"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="技术方向" prop="majorId">
          <el-select
            v-model="classForm.majorId"
            placeholder="请选择技术方案"
            :disabled="modalState == 'VIEW'"
          >
            <el-option
              v-for="item in major"
              :key="item.id"
              :label="item.majorName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目经理" prop="projectManagerMessageId">
          <el-select
            v-model="classForm.projectManagerMessageId"
            placeholder="请选择项目经理"
            :disabled="modalState == 'VIEW'"
          >
            <el-option
              v-for="item in majorPm"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="教室" prop="classroomId">
          <el-select
            v-model="classForm.classroomId"
            placeholder="请选择教室"
            :disabled="modalState == 'VIEW'"
          >
            <el-option
              v-for="item in classroom"
              :key="item.classroomId"
              :label="item.classroomName"
              :value="item.classroomId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级状态">
          <el-select
            v-model="classForm.status"
            placeholder="请选择"
            :disabled="modalState == 'VIEW'"
          >
            <el-option
              v-for="item in statusData"
              :key="item.code"
              :label="item.text"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer" v-if="modalState != 'VIEW'">
          <el-button type="primary" @click="submitClassForm(classFormRef)"
            >提交</el-button
          >
          <el-button @click="resetClassForm(classFormRef)">重置</el-button>
        </span>
      </template>
    </el-dialog>
  </main>
</template>

<style lang="scss">
@import "@/assets/scss/global.scss";

.student-list {
  padding: 20px 0;
}
.batch-processing {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.class_refresh {
  &:hover {
    color: $color-theme;
  }
}
</style>
